package cn.chiship.framework.upms.biz.user.controller;

import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.framework.upms.biz.user.entity.*;
import cn.chiship.framework.upms.biz.user.pojo.dto.UpmsUserDto;
import cn.chiship.framework.upms.biz.user.service.UpmsUserOrganizationService;
import cn.chiship.framework.upms.biz.user.service.UpmsUserService;
import cn.chiship.sdk.core.annotation.Authorization;
import cn.chiship.sdk.core.annotation.NoParamsSign;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseController;
import cn.chiship.sdk.framework.base.BaseService;
import cn.chiship.sdk.framework.pojo.vo.PageVo;
import cn.chiship.sdk.framework.util.ServletUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

/**
 * 用户控制层 2021/9/27
 *
 * @author lijian
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UpmsUserController extends BaseController<UpmsUser, UpmsUserExample> {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsUserController.class);

    @Resource
    private UpmsUserService upmsUserService;

    @Resource
    UpmsUserOrganizationService upmsUserOrganizationService;

    @Override
    public BaseService getService() {
        return upmsUserService;
    }

    @SystemOptionAnnotation(describe = "用户分页")
    @ApiOperation(value = "用户分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", defaultValue = "10", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "所属单位", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "用户名", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "realName", value = "真实姓名", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "mobile", value = "手机号", dataTypeClass = String.class, paramType = "query")
    })
    @Authorization
    @NoParamsSign
    @GetMapping(value = "/page")
    public ResponseEntity<BaseResult> page(@RequestParam(required = false, value = "orgId") String orgId,
                                           @RequestParam(required = false, value = "userName") String userName,
                                           @RequestParam(required = false, value = "realName") String realName,
                                           @RequestParam(required = false, value = "mobile") String mobile) {
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        UpmsUserExample.Criteria criteria = upmsUserExample.createCriteria();
        List<String> userIds = new ArrayList<>();
        if (!StringUtil.isNullOrEmpty(orgId)) {
            UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample();
            upmsUserOrganizationExample.createCriteria().andOrganizationIdEqualTo(orgId);
            List<UpmsUserOrganization> upmsUserOrganizations = upmsUserOrganizationService
                    .selectByExample(upmsUserOrganizationExample);
            for (UpmsUserOrganization upmsUserOrganization : upmsUserOrganizations) {
                userIds.add(upmsUserOrganization.getUserId());
            }
            if (userIds.isEmpty()) {
                userIds.add("-1");
            }
        }
        if (!userIds.isEmpty()) {
            criteria.andIdIn(userIds);
        }
        if (!StringUtil.isNullOrEmpty(userName)) {
            criteria.andUserNameLike(userName + "%");
        }
        if (!StringUtil.isNullOrEmpty(realName)) {
            criteria.andRealNameLike(realName + "%");
        }
        if (!StringUtil.isNullOrEmpty(mobile)) {
            criteria.andMobileLike(mobile + "%");
        }
        PageVo pageVo = super.page(upmsUserExample);
        return super.responseEntity(upmsUserService.page(pageVo));
    }

    @ApiOperation(value = "用户分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", defaultValue = "10", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "所属单位", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "orgCategory", value = "单位类型", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "includeChildren", value = "是否包含下级部门(true:包含 false：不包含)", dataTypeClass = Boolean.class, paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键字（用户名、姓名、手机、部门职位）", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "用户名", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "realName", value = "真实姓名", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "mobile", value = "手机号", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "orgJob", value = "部门职位", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "isInner", value = "是否内部员工 0：否 1：是", dataTypeClass = Byte.class, paramType = "query")
    })
    @Authorization
    @NoParamsSign
    @GetMapping(value = "/pageV2")
    public ResponseEntity<BaseResult> pageV2(@RequestParam(required = false, value = "orgId") String orgId,
                                             @RequestParam(required = false, value = "orgCategory") String orgCategory,
                                             @RequestParam(required = false, value = "includeChildren") Boolean includeChildren,
                                             @RequestParam(required = false, value = "keyword") String keyword,
                                             @RequestParam(required = false, value = "userName") String userName,
                                             @RequestParam(required = false, value = "realName") String realName,
                                             @RequestParam(required = false, value = "mobile") String mobile,
                                             @RequestParam(required = false, value = "orgJob") String orgJob,
                                             @RequestParam(required = false, value = "isInner") Byte isInner) {
        PageVo pageVo = ServletUtil.getPageVo();

        HashMap<String, Object> paramsMap = new HashMap(7);
        paramsMap.put("orgId", orgId);
        paramsMap.put("orgCategory", orgCategory);
        paramsMap.put("realName", realName);
        paramsMap.put("userName", userName);
        paramsMap.put("mobile", mobile);
        paramsMap.put("orgJob", orgJob);
        paramsMap.put("keyword", keyword);
        if (!StringUtil.isNull(isInner)) {
            paramsMap.put("isInner", isInner);
        }
        if (!StringUtil.isNull(includeChildren)) {
            paramsMap.put("includeChildren", includeChildren);
        }
        paramsMap.put("sort", pageVo.getSort());
        return super.responseEntity(upmsUserService.page(pageVo, paramsMap));
    }

    @SystemOptionAnnotation(describe = "用户列表")
    @ApiOperation(value = "用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", dataTypeClass = String.class, paramType = "query")
    })
    @Authorization
    @GetMapping(value = "/list")
    public ResponseEntity<BaseResult> list(@RequestParam(required = false, value = "userName") String userName) {
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        UpmsUserExample.Criteria criteria = upmsUserExample.createCriteria();
        if (!StringUtil.isNull(userName)) {
            criteria.andUserNameLike("%" + userName + "%");
        }
        Map<String, List<UpmsUser>> map = new TreeMap(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        List<UpmsUser> upmsUsers = upmsUserService.selectByExample(upmsUserExample);
        for (UpmsUser user : upmsUsers) {
            String firstLetter = user.getUserPinyin().substring(0, 1);
            if (map.containsKey(firstLetter)) {
                List<UpmsUser> temp = map.get(firstLetter);
                temp.add(user);
                map.put(firstLetter, temp);
            } else {
                List<UpmsUser> temp = new ArrayList<>();
                temp.add(user);
                map.put(firstLetter, temp);
            }
        }
        return super.responseEntity(BaseResult.ok(map));
    }

    @SystemOptionAnnotation(describe = "根据手机号获取用户")
    @ApiOperation(value = "根据手机号获取用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", dataTypeClass = String.class, paramType = "query"),})
    @GetMapping(value = "getUserByMobile")
    public ResponseEntity<BaseResult> getUserByMobile(@RequestParam(value = "mobile") String mobile) {
        return super.responseEntity(upmsUserService.getUserByMobile(mobile));
    }

    @SystemOptionAnnotation(describe = "根据指定字段校验数据是否存在")
    @ApiOperation(value = "根据指定字段校验数据是否存在")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "field", value = "字段", required = true, dataTypeClass = String.class,
                    paramType = "query"),
            @ApiImplicitParam(name = "value", value = "值", required = true, dataTypeClass = String.class,
                    paramType = "query"),})
    @GetMapping(value = "validateExistByField")
    @Override
    public ResponseEntity<BaseResult> validateExistByField(@RequestParam(required = false, value = "id") String id,
                                                           @RequestParam(value = "field") String field, @RequestParam(value = "value") String value) {
        return super.responseEntity(upmsUserService.validateExistByField(id, field, value));
    }

    @SystemOptionAnnotation(describe = "保存用户", option = BusinessTypeEnum.SYSTEM_OPTION_SAVE)
    @ApiOperation(value = "保存用户")
    @Authorization
    @PostMapping(value = "save")
    @NoParamsSign
    public ResponseEntity<BaseResult> save(@RequestBody @Valid UpmsUserDto upmsUserDto) {
        upmsUserService.saveUser(upmsUserDto);
        return super.responseEntity(BaseResult.ok());

    }

    @SystemOptionAnnotation(describe = "更新用户", option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path"),})
    @ApiOperation(value = "更新用户")
    @Authorization
    @PostMapping(value = "update/{id}")
    @NoParamsSign
    public ResponseEntity<BaseResult> update(@PathVariable("id") String id,
                                             @RequestBody @Valid UpmsUserDto upmsUserDto) {
        upmsUserService.updateUser(id, upmsUserDto);
        return super.responseEntity(BaseResult.ok());
    }

    @SystemOptionAnnotation(describe = "删除用户", option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE)
    @ApiOperation(value = "删除用户")
    @Authorization
    @PostMapping(value = "remove")
    public ResponseEntity<BaseResult> remove(@RequestBody @Valid List<String> ids) {
        return super.responseEntity(upmsUserService.removeUser(ids));
    }

    @SystemOptionAnnotation(describe = "初始化密码", option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE)
    @ApiOperation(value = "初始化密码")
    @Authorization
    @PostMapping(value = "initialPassword")
    public ResponseEntity<BaseResult> initialPassword(@RequestBody @Valid List<String> ids) {
        return super.responseEntity(upmsUserService.initialPassword(ids));
    }

    @SystemOptionAnnotation(describe = "获得当前登录用户详细信息")
    @ApiOperation(value = "获得当前登录用户详细信息")
    @GetMapping("/getCurrentUserDetailedInfo")
    @Authorization
    public ResponseEntity<BaseResult> getCurrentUserDetailedInfo() {
        return super.responseEntity(upmsUserService.selectDetailsByPrimaryKey(getUserId()));
    }

    @SystemOptionAnnotation(describe = "用户启用&锁定", option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE)
    @ApiOperation(value = "用户启用&锁定")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path"),})
    @Authorization
    @PostMapping(value = "changeIsLocked/{id}")
    public ResponseEntity<BaseResult> changeIsLocked(@PathVariable("id") String id,
                                                     @RequestBody @Valid Boolean isLocked) {
        return super.responseEntity(upmsUserService.changeIsLocked(id, isLocked));
    }

    @ApiOperation(value = "根据用户获得所有权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "主键", dataTypeClass = String.class, paramType = "query"),})
    @Authorization
    @GetMapping(value = "listPermissionByUserId")
    public ResponseEntity<BaseResult> listPermissionByUserId(@RequestParam(value = "userId") String userId) {
        return super.responseEntity(upmsUserService.getPermission(userId));
    }

    @SystemOptionAnnotation(describe = "通知公告发布", option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE)
    @ApiOperation(value = "通知公告发布")
    @ApiImplicitParams({})
    @PostMapping(value = "publishNotice/{noticeId}")
    public ResponseEntity<BaseResult> publishNotice(@PathVariable("noticeId") String noticeId,
                                                    @Valid @RequestBody String scope) {
        return super.responseEntity(upmsUserService.publishNotice(noticeId, scope));
    }

}
